package team.kirohuji.config;

import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoException;

@Configuration
@EnableMongoRepositories(basePackages = "team.kirohuji.repository.mongodb")
@ImportResource(locations={"classpath:spring-config-mongodb.xml"}) 
public class MongoConfig {
	/*@Value("${spring.data.mongodb.database}")
	private String database;
	@Value("${spring.data.mongodb.}")
	private String host;
	@Value("${spring.data.mongodb.password}")
	private String password;
	@Value("${spring.data.mongodb.port}")
	private String port;
	@Value("${spring.data.mongodb.username}")
	private String username;

	@Bean
	public MongoMappingContext mongoMappingContext() {
		MongoMappingContext mappingContext = new MongoMappingContext();
		return mappingContext;
	}

	@Bean
	public DefaultMongoTypeMapper defaultMongoTypeMapper() {
		return new DefaultMongoTypeMapper();
	}

	@Bean // 使用自定义的typeMapper去除写入mongodb时的“_class”字段
	public MappingMongoConverter mappingMongoConverter1() throws Exception {
		DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(dbFactory());
		MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, this.mongoMappingContext());
		converter.setTypeMapper(new DefaultMongoTypeMapper(null));
		return converter;
	}

	@Bean
    @Primary  
	public MongoDbFactory dbFactory() throws UnknownHostException {
		return new SimpleMongoDbFactory(mongoClient(), database);
	}

	@Bean
	public MongoClient mongoClient() throws UnknownHostException {
		MongoClientOptions.Builder build = new MongoClientOptions.Builder();
		MongoClientOptions myOptions = build.build();
		try {
			// 数据库连接实例
			MongoClient mongoClient = new MongoClient(host, myOptions);
			return mongoClient;
		} catch (MongoException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Bean
	@Primary
	public MongoTemplate mongoTemplate() throws Exception {
		return new MongoTemplate(this.dbFactory(), this.mappingMongoConverter1());
	}*/
}